package com.tjl.foodapp.utils;

import android.os.AsyncTask;


import com.tjl.foodapp.Utils;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;


import cn.hutool.core.io.FileUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Request;

public class ImageUploadTask extends AsyncTask<Map<String,Object>, Void, JSONObject> {

    //外部传入 请求完成时逻辑
    public interface OnUploadResultHandler {
        void handle(JSONObject result) throws JSONException;
    }
    private OnUploadResultHandler listener;
    private static final MediaType MEDIA_TYPE_IMAGE_JPEG = MediaType.parse("image/jpeg");
    private static final MediaType MEDIA_TYPE_IMAGE_PNG = MediaType.parse("image/png");

    public ImageUploadTask(OnUploadResultHandler listener) {
        this.listener = listener;
    }


    @Override
    protected JSONObject doInBackground(Map<String, Object>... maps) {
        Map<String, Object> map = maps[0];
        if (StringUtils.isBlank(map.get("userId").toString())
            || map.get("file") == null){
            return null;
        }
        File imageFile = (File) map.get("file");
        int userId = Integer.parseInt(map.get("userId").toString());
        MediaType mediaType = null;
        String extName = FileUtil.extName(imageFile);
        if ("jpg".equals(extName) || "jpeg".equals(extName) ){
            mediaType =  MEDIA_TYPE_IMAGE_JPEG;
        } else if ("png".equals(extName)){
            mediaType = MEDIA_TYPE_IMAGE_PNG;
        }else{
            mediaType = MEDIA_TYPE_IMAGE_PNG;
        }

        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("imageFile", imageFile.getName(),
                        RequestBody.create(mediaType, imageFile))
                .addFormDataPart("userId", String.valueOf(userId))
                .build();

        Request request = new Request.Builder()
                .url(Utils.urlBase + "and_upload_advatar.do")
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            JSONObject jsonObject = new JSONObject(response.body().string());
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(JSONObject res) {
        super.onPostExecute(res);
        if (res == null){
            res = new JSONObject();
            try {
                res.put("flag",false);
                res.put("msg","服务器可能开小差了");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        // 将响应值返回给外部调用者
        try {
            listener.handle(res);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

    }
}